from PySide6.QtWidgets import QTableWidgetItem

from controller.user_controller import UserController
from model.logic_models import UserModel
from view.main_window import MainWindow
from model.database_manager import Engine, Base


def transform_table(table, data=None):
    if data is None: data = {None: None}
    table.setRowCount(len(data))
    table.setColumnCount(len(data[0]))
    table.setHorizontalHeaderLabels(list(data[0].keys()))

    for row_idx, row_data in enumerate(data):
        for col_idx, col_data in enumerate(row_data):
            table.setItem(row_idx, col_idx, QTableWidgetItem(str(row_data[col_data])))

def _show_all_users():
    user_controller = UserController()
    users_data = user_controller.get_all_users_for_display()
    if not users_data:
        print("No users found")
    return users_data

def initialize_database():
    print("Initializing database")
    try:
        Base.metadata.create_all(bind=Engine)
        print("Database initialized")
    except Exception as e:
        print(e)

class MainController:
    def __init__(self, main_window=None):
        self.main_window = None
        self.user_controller = UserController()

    def show_main_window(self):
        initialize_database()
        self.main_window = MainWindow()
        add_user_button = self.main_window.add_user_button
        add_user_button.clicked.connect(self.on_add_user_button_clicked)
        self.main_window.show()
        print("Showing principal window")
        self.users_table()

    def users_table(self):
        table = self.main_window.table_users
        data = _show_all_users()
        transform_table(table, data)

    def on_add_user_button_clicked(self):
        user_name = self.main_window.name_edit.text()
        user_lastname = self.main_window.lastname_edit.text()

        if self.user_controller.add_user(user_name, user_lastname):
            self.main_window.name_edit.clear()
            self.main_window.lastname_edit.clear()
            self.main_window.display_status_message(f"Added {user_name} user.")
            self.users_table()
        else:
            self.main_window.display_status_message(f"Error adding user {user_name}.")
            print("User already exists")